package cn.tedu.lbs.marketing.web.controller;

import cn.tedu.lbs.marketing.web.service.UserCouponService;
import cn.tedu.lbs.marketing.web.utils.AuthenticationContextUtil;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.model.Result;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.pojo.marketing.param.UserCouponsParam;
import com.tarena.lbs.pojo.marketing.query.UserCouponCodeQuery;
import com.tarena.lbs.pojo.marketing.query.UserCouponQuery;
import com.tarena.lbs.pojo.marketing.vo.UserCouponsVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;

/**
 * 当前模块 处理和用户 领取优惠券
 * 用户查询 我的优惠券等业务
 */
@RestController
@Slf4j
public class UserCouponController {
    @Autowired
    private UserCouponService userCouponService;
    //强调,一般用户身份userId 之前都是在业务层解析的
    //这个接口为了 实现业务的复用 在控制层解析userId 补充到业务入参里
    @PostMapping("/marketing/user/receive/save")
    public Result<Void> receiveCoupon(@RequestBody UserCouponsParam param)
            throws BusinessException, ExecutionException, InterruptedException {
        UserPrinciple userPrinciple = AuthenticationContextUtil.get();
        Asserts.isTrue(userPrinciple==null,new BusinessException("-2","用户认证解析失败"));
        param.setUserId(userPrinciple.getId());
        log.info("CONTROLLER层,用户领取优惠券,入参:{}",param);
        //调用 业务层 领取 执行业务逻辑 统计业务方法执行时间
        long start=System.currentTimeMillis();
        userCouponService.receiveCoupon(param);
        long end=System.currentTimeMillis();
        log.info("CONTROLLER层,用户领取优惠券,执行时间:{}ms",end-start);
        return Result.success();
    }
    //手机小程序端 查看我的优惠券
    @PostMapping("/marketing/user/receive/list")
    public Result<PageResult<UserCouponsVO>> myCoupons(@RequestBody UserCouponQuery couponQuery)
        throws BusinessException{
        return new Result<>(userCouponService.myCoupons(couponQuery));
    }
    //查询我的优惠券详情 展示券码二维码
    @PostMapping("/marketing/user/receive/detail")
    public Result<UserCouponsVO> detail(@RequestBody UserCouponCodeQuery query)
        throws BusinessException{
        return new Result<>(userCouponService.detail(query));
    }
}
